#![feature(proc_macro_hygiene, decl_macro)]

#[macro_use]
extern crate rocket;

use std::fs;
use std::fs::metadata;
use std::io::Cursor;
use ho_string::HoString;
use ho_file::HoFile;
use rocket::{Config, custom, Response};
use rocket::config::Environment;
use rocket::http::ContentType;
use rocket_contrib::serve::StaticFiles;

fn get_menu() -> HoString {
    return HoFile::read_file_all("static/menu.html", "");
}

#[get("/")]
fn index() -> Response<'static> {
    let content: HoString = HoFile::read_file_bytes("db.txt");
    let len: usize = content.split_str("\n", -1).len();
    let mut html: HoString = HoFile::read_file_all("static/index.html", "");
    let mut response: Response = Response::new();
    let mut src_str_vec: Vec<&[u8]> = Vec::new();
    let mut replace_str_vec: Vec<&[u8]> = Vec::new();
    src_str_vec.push("{{menu}}".as_bytes());
    src_str_vec.push("{{student_count}}".as_bytes());
    let binding: HoString = get_menu();
    let binding1: String = len.to_string();
    replace_str_vec.push(binding.to_bytes());
    replace_str_vec.push(binding1.as_bytes());
    html = html.replace_bytes_vec(src_str_vec, replace_str_vec);
    response.set_header(ContentType::HTML);
    response.set_sized_body(Cursor::new(html.to_string().to_owned()));
    return response;
}

fn main() {
    if let Err(_e) = metadata("db.txt") {
        let _ = fs::write("db.txt", "");
    }
    let config: Config = Config::build(Environment::Development)
        .address("0.0.0.0")
        .port(80)
        .workers(1)
        .unwrap();
    let routes = routes![
        index
    ];
    custom(config)
        .mount("/", routes)
        .mount("/static", StaticFiles::from("static"))
        .mount("/uploads", StaticFiles::from("uploads"))
        .launch();
}
